using System;
using System.Collections;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

using SchemaMonitor;
using Framework;

public partial class pages_sections_usercontrols_UCSection : UserControl 
{     
    #region Members
    private CSection _section; 
    private IList _sortedList;
	private CSectionList _siblings;
    #endregion 
    
    #region Interface
    public void Display(CSection s, IList sortedList) 
    { 
        if (Parent.Controls.Count % 2 == 0) 
            row.Attributes.Add("class", "alt_row"); 
        
        _section = s; 
        _sortedList = sortedList;
		_siblings = s.Book.Sections;
        
        //Show/Hide Columns 
        colOrder.Visible = (sortedList.Count > 1);
		CTextbox.SetNumber(txtOrder, s.SectionSortOrder);

		btnDelete.ID = string.Concat("b", s.SectionId); ;
		txtOrder.ID = string.Concat("t", s.SectionId);
  
        litNumber.Text = Convert.ToString(sortedList.IndexOf(s) + 1);
        lnkSectionName.Text = (string)(s.SectionName.Length == 0 ? "..." : s.SectionName); 
        lnkSectionName.NavigateUrl = CSitemap.SectionEdit(s.SectionId);
		litChapters.Text = CUtilities.CountSummary(s.Chapters, "post", "none");
    } 
    #endregion 
    
    #region Event Handlers 
    protected void btnMoveUp_Click(object sender, System.Web.UI.ImageClickEventArgs e)
    { 
        new CSectionList(_siblings).MoveUp(_section); 
        Refresh(); 
    } 
    protected void btnMoveDn_Click(object sender, System.Web.UI.ImageClickEventArgs e)
    { 
        new CSectionList(_siblings).MoveDown(_section); 
        Refresh(); 
    }
    protected void btnDelete_Click(object sender, ImageClickEventArgs e) 
    {
        _section.Delete(); 
        Refresh(); 
    } 
    #endregion 
    
    #region Private
    private void Refresh() 
    { 
        Response.Redirect(Request.RawUrl); 
    }
	#endregion

	protected void txtOrder_TextChanged(object sender, EventArgs e)
	{
		var i = CTextbox.GetInteger(txtOrder);
		if (i == int.MinValue)
		{
			_section.SectionSortOrder = i;
			_section.Save();
			_siblings.Sort();
			return;
		}

		if (i < 0)
			i = 0;
		if (i >= _siblings.Count)
			i = _siblings.Count-1;

		var temp = new CSectionList(_siblings);
		temp.Remove(_section);
		temp.Insert(i, _section);
		temp.ResetSortOrder();
		_siblings.Sort();
		Refresh();
	}
} 
